package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*
* token的工具类
* */
public class JwtUtil {

    //签名(设置一个唯一签名)
 private   static   SecretKey secretKey = Keys.hmacShaKeyFor("8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92".getBytes());
    //过期时间:   默认单位:毫秒
  private static   long expireTime= 6000*60*1000l;
    //创建token
    /*
    *  把登录用户的信息写入到token中
    *   userId 登录用户的唯一标识
    *   account: 用户的账号(后台系统的账号: userName   app系统: phone)
    *  eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAA_6tWKi1OLfJMUbIy1FFKTE7OL80rUbJSqspIzEsvTsxTqgUAhyLRtyEAAAA.pL_vCRsh8WMefXUT7tkbd582qzpsMK7KndsjxtNb5kkFxWoQQ3d33qulgoo5hn4ZfK2zl9sq1ITUTdCRXzwU7w
    * */
/*public  static  String createToken(Long userId,String account){
     //负载: 设置登录的信息
    Map payload=new HashMap();
    payload.put("userId",userId);
    payload.put("account",account);


    String token = Jwts.builder()
            .setSubject("user-info") //给当前的token设置一个主题（分类）
            .setClaims(payload)
            .setExpiration(new Date(System.currentTimeMillis() + expireTime))    //设置token的过期时间
            .signWith(secretKey)
            .compressWith(CompressionCodecs.GZIP)  //压缩token的信息
            .compact();
    return token;
}*/

    public  static  String createToken(Long userId,String account){



        String token = Jwts.builder()
                .setSubject("user-info") //给当前的token设置一个主题（分类）
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))    //设置token的过期时间
                .claim("userId",userId)
                .claim("account",account)
                .signWith(secretKey)
                .compressWith(CompressionCodecs.GZIP)  //压缩token的信息
                .compact();
        return token;
    }

    //解析token
    public static  Claims parserToken(String token){
        try {
             //解析token的内容: 注意必须提供创建token时的签名
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
             //获取token中的负载数据
            Claims body = claimsJws.getBody();
            return body;
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);

        }catch (Exception e){
             e.printStackTrace();
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }



    public static void main(String[] args) {
        String token = createToken(1L, "zhangsan");
        System.out.println(token);
        try {
            Thread.sleep(expireTime+5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Claims claims = parserToken(token);

        Long userId = claims.get("userId", Long.class);
        String account = claims.get("account", String.class);

        System.out.println(account+","+userId);

    }

}
